#include <stdio.h>
#include <stdlib.h>
#include "xlist.h"

int list_create(list_st **ptr)
{
	list_st *newnode = NULL;
	list_st *cur = NULL;
	while(1)
	{
		int num;
		newnode = malloc(sizeof(*newnode));
		if(newnode == NULL)
			return -1;
		scanf("%d",&num);
		if(num == -1)
			break;
		newnode->data = num;
		newnode->next = NULL;
		list_insert_end(ptr,newnode,&cur);
	}
}

int list_insert_end(list_st **ptr,list_st *newnode,list_st **cur)
{
	if(*ptr == NULL)
	{
		*ptr = newnode;
	}
	else
	{
		(*cur)->next = newnode;
	}
	newnode->next = *ptr;
	*cur = newnode;
	return 0;
}

list_st *list_delete(list_st *ptr,Datatype *data)
{
	list_st *x = ptr;
	list_st *prev = NULL;
	while(x)
	{
		if(x->data == *data)
			break;
		prev = x;
		x = x->next;
	}
	if(x == NULL)
		return ptr;
	else
	{
		//删除点为头结点时，找到最后结点的位置，将它的next指针指向新的头结点构成循环
		if(x == ptr)
		{
			list_st *cur = ptr;
			list_st *f;
			do
			{
				f = cur;
				cur = cur->next;
			}while(cur != ptr);
			ptr = x->next;
			f->next = ptr;
		}
		else
		{
			prev->next = x->next;
		}
		free(x);
	}
	return ptr;
}

void list_display(list_st *ptr)
{
	if(ptr == NULL)
		return ;
	list_st *p = ptr;
	do
	{
		printf("%d ",p->data);
		p = p->next;
	}while(p != ptr);
	printf("\n");	
}

void list_destroy(list_st *ptr)
{
	list_st *p = ptr;
	list_st *next = NULL;
	do
	{
		next = p->next;
		free(p);
		p = next;
	}while(p != ptr);
}

